package com.aramis.mydytt

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.aramis.mydytt.db.DBManager
import com.aramis.mydytt.ui.recommend.MainRecommendFragment
import com.aramis.mydytt.ui.search.MainSearchFragment
import com.aramis.mydytt.ui.topic.MainTopicFragment
import com.aramis.mydytt.ui.user.MainUserFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.bottomnavigation.LabelVisibilityMode
import kotlin.math.abs

class MainActivity : AppCompatActivity() {
    private var firstBackTime = 0L
    private lateinit var viewPager: ViewPager2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        val navView: BottomNavigationView = findViewById(R.id.nav_view)
        navView.labelVisibilityMode = LabelVisibilityMode.LABEL_VISIBILITY_LABELED

        viewPager = findViewById(R.id.view_pager)
        viewPager.adapter = ViewPagerAdapter(this)
        viewPager.isUserInputEnabled = false
        viewPager.offscreenPageLimit = 3
        navView.setOnNavigationItemSelectedListener {
            val position = when (it.itemId) {
                R.id.navigation_recommend -> 0
                R.id.navigation_search -> 1
                R.id.navigation_topic -> 2
                else -> 3
            }
            val oldPosition = viewPager.currentItem
            viewPager.setCurrentItem(position, abs(oldPosition - position) == 1)
            true
        }
    }

    private class ViewPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
        override fun getItemCount(): Int = 4

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> MainRecommendFragment()
                1 -> MainSearchFragment()
                2 -> MainTopicFragment()
                else -> MainUserFragment()
            }
        }

    }

    override fun onBackPressed() {
        if (firstBackTime == 0L || System.currentTimeMillis() - firstBackTime > 1500L) {
            firstBackTime = System.currentTimeMillis()
            Toast.makeText(this, "再按一次，退出app", Toast.LENGTH_SHORT).show()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        DBManager.close()
        super.onDestroy()
    }
}